package com.fanli.scheduler.interceptor;

import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fanli.scheduler.utils.CommonUtils;
import com.fanli.scheduler.utils.Constant;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by wei.shen on 2015/9/1.
 */
public class ApplicationLoginIntercepor extends HandlerInterceptorAdapter {
    private static final String LOGIN_URL = "/resources/pages/login.html";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        HttpSession httpSession = request.getSession(true);
        String obj = (String) httpSession.getAttribute(Constant.AUTH_USER_KEY);
//        System.err.println(obj);
        if (CommonUtils.isEmpty(obj)) {
//        	System.err.println("false");
//            httpServletResponse.sendRedirect("http://localhost:8080/assets/pages/login.html");
        	String requestType = request.getHeader("X-Requested-With");
			if ("XMLHttpRequest".equals(requestType)) {
				response.setStatus(HttpStatus.UNAUTHORIZED.value());// 设置http状态为401
				response.setHeader("sessionstatus", "timeout");// 在响应头设置session状态
				return false;
			}
			response.sendRedirect(LOGIN_URL);
            return false;
        } else return true;
        
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
